------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
-- local function language_change_say(theNPC)
--     theNPC.CHAT_TABLE = {}
--     if theNPC.npc_base_lib:Get_Language() == "ch" then
--         theNPC.CHAT_TABLE.it_is_for_you = "这个给你"
--     else
--         theNPC.CHAT_TABLE.it_is_for_you = "This is for you"    
--     end
-- end

local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_ask_for_razor"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local function talk_fn(theNPC,_table)
    if _table and _table.talk then
        theNPC:DoTaskInTime(0.3,function()

            -- theNPC.npc_base_lib:Say(_table.talk)     
            if theNPC.____ask_item ~= "reviver" then
                theNPC.____ask_item = "reviver"
            else
                theNPC.____ask_item = "amulet"
            end

            theNPC.npc_base_lib:Show_Chat_Bubble({
                image = theNPC.____ask_item,
                num = 1,
                height = 4.3
            })


        end)
    end
end

local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            if theNPC.event_step ~= nil then
                return
            end
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.too_late)
            print("Warning : npc time out and leave")
        end)
    end
end

local function Chat_Bubble_Fn(theNPC)
    theNPC.npc_base_lib:Show_Chat_Bubble({
        image = "razor",
        num = 1,
        -- height = 4.3
    })
end

local function Item_Get_Event_Init(theNPC)
    theNPC:ListenForEvent("itemget",function(theNPC,_table)  ----    进入删除的话，不会触发这个 event

    end)
 
    -------------------------------------------------------------------------
    local function ShouldAcceptItem(inst, item)
        if item and item.prefab == "razor" then
            return true
        end
    end
    local function OnGetItem(inst, giver, item)
        print("OnGetItem ,Giver :",giver,item)
        -- theNPC:PushEvent()
        if item.prefab == "razor" then
            inst.__razor = item
            theNPC.event_step = 1
            theNPC.npc_base_lib:Hide_Chat_Bubble()
        end
    end
    local function abletoaccepttest(inst,item,giver)
        if item and item.prefab == "razor" then
            return true
        end
    end
    theNPC.components.trader:SetAcceptTest(ShouldAcceptItem)
    theNPC.components.trader.onaccept = OnGetItem
    theNPC.components.trader.deleteitemonaccept = false
    theNPC.components.trader:SetAbleToAcceptTest(abletoaccepttest)
    -------------------------------------------------------------------------
    -- -- 搜索附近地上的
    -- theNPC.find_around_item_task =   theNPC:DoPeriodicTask(0.3,function()
    --     if theNPC.event_step ~= nil then
    --         if theNPC.find_around_item_task then
    --             theNPC.find_around_item_task:Cancel()
    --             theNPC.find_around_item_task = nil
    --         end
    --         return
    --     end
    --     local canthavetags = { "companion","isdead","player","INLIMBO", "notarget", "noattack", "flight", "invisible", "playerghost" ,"chester","hutch","wall","structure"}
    --     local x,y,z = theNPC.Transform:GetWorldPosition()
    --     local ents = TheSim:FindEntities(x, 0, z, 3, {"razor"}, canthavetags, nil)
    --     if #ents > 0 then
    --         for k, item in pairs(ents) do
    --             if item and item:IsValid() and item.prefab == "reviver" and
    --                 item.components.inventoryitem and item.components.inventoryitem.owner == nil
    --             then
    --                 OnGetItem(theNPC,nil,item)
    --                 item:Remove()
    --             end
    --         end 
    --     end
    -- end)
    -------------------------------------------------------------------------

end


local function GiveItem(theNPC)
    local times_check = theNPC.npc_everything_data:Add("times_check",1)
    if times_check ~= 1 and  times_check%3 ~= 0 then
        return false
    end



    if theNPC.npc_everything_data:Get("item_num") == nil then
        if TUNING.NPC_CONFIG.REWARDS_LESS == true then
            theNPC.npc_everything_data:Add("item_num",math.random(10,20))
        else
            theNPC.npc_everything_data:Add("item_num",math.random(20,40))
        end
    end

    ------ woodie_npc  wolfgang_npc webber_npc wagstaff_2_npc  waxwell_npc
    local items = {"beardhair","beardhair"}
    if theNPC.prefab == "woodie_npc" then
        items = {"beardhair","beardhair","beardhair","beardhair","cutgrass","deer_antler3","goose_feather","furtuft"}
    elseif theNPC.prefab == "webber_npc" then
        items = {"beardhair","silk","beardhair","silk","silk","silk","silk","silk"}
    elseif theNPC.prefab == "wagstaff_2_npc" then
        items = {"beardhair","beardhair","beardhair","gears","beardhair"}       
    elseif theNPC.prefab == "waxwell_npc" then
        items = {"beardhair","beardhair","nightmarefuel","nightmarefuel","nightmarefuel"}             
    elseif theNPC.prefab == "woodlegs_npc" then
        items = {"barnacle","barnacle","barnacle","beardhair","twigs","log","barnacle","barnacle","barnacle"}
    end

    local ret_item_name = theNPC.npc_base_lib:GetRandom(items)

    -- theplayer.components.npc_base_lib:Throw_Out_Items({ name = "icecream" ,num = math.random(3,8), range = 8 ,height = 10})

    local theCamp = theNPC.__theCamp
    theNPC.npc_base_lib:Throw_Out_Items({
        target = theCamp,
        name = ret_item_name,
        num = 1,
        range = math.random(5),
        height = math.random(10)
    })

    if theNPC.npc_everything_data:Add("item_num",-1) < 0 then
        return true
    else
        return false
    end 

end


local function Hide_in_camp(theNPC)
    theNPC:Hide()
    theNPC.AnimState:ClearOverrideSymbol("beard")
    local x,y,z = theNPC.Transform:GetWorldPosition()
    theNPC.Transform:SetPosition(x,100,z)
    local theCamp = SpawnPrefab("portabletent")
    theCamp.Transform:SetPosition(x,0,z)
    theNPC.__theCamp = theCamp
    SpawnPrefab("collapse_big").Transform:SetPosition(x, y, z)
    theCamp:AddTag("INLIMBO")
    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    theCamp:DoPeriodicTask(1.5,function()
        theCamp.AnimState:PushAnimation(theCamp.sleep_anim)
    end)
end


local function Give_Back_razor(theNPC,theplayer)
    local x,y,z = theNPC.Transform:GetWorldPosition()
    theNPC.Transform:SetPosition(x,0,z)

    theNPC.__theCamp:Remove()
    theNPC:Show()
    SpawnPrefab("collapse_big").Transform:SetPosition(x, 0, z)

    local razor = theNPC.__razor
    theNPC.components.inventory:DropEverything()
    razor:DoTaskInTime(6,function()
        razor.npc_base_lib:Say(theNPC.CHAT_TABLE.razor_say)
    end)
    theplayer:DoTaskInTime(1.5,function()
        theplayer.components.npc_base_lib:Wisper(theNPC.CHAT_TABLE.announce)
    end)
end

local function beard_grow(theNPC)
    if theNPC.prefab == "wilson_npc" then
        theNPC.AnimState:OverrideSymbol("beard", "beard", "beard_long")
    elseif theNPC.prefab == "webber_npc" then
        theNPC.AnimState:OverrideSymbol("beard", "beard_silk", "beardsilk_long")
    end        
end
-------------------------------------------------------------------------------------------------------------------------------------------------
local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)
    Item_Get_Event_Init(theNPC)
    -- theNPC.npc_base_lib:Equip_Random_Hat()
    -- theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    -- theNPC:AddTag("INLIMBO")
    -- theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_event = inst.prefab
    beard_grow(theNPC)

    theNPC:AddTag("alltrader")
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then
        if theNPC.npc_everything_data:Add("wait time 000",1) % 10 == 0 then
            Chat_Bubble_Fn(theNPC)
        end
        theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 7,random_range_flag = true , mid_reflash_range = 2})
        
    elseif theNPC.event_step == 1 then
        theNPC:AddTag("Unable_To_Refuse")
        -- theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.it_is_for_you)
        -- GiveItem(theNPC)
        if theNPC.npc_everything_data:Add("time_wait_000",1) == 1 then
            Hide_in_camp(theNPC)
        elseif theNPC.npc_everything_data:Get("time_wait_000") >= 3 then
            
            theNPC.event_step = theNPC.event_step + 1
        end

    elseif theNPC.event_step == 2 then
        -- if theNPC.npc_everything_data:Add("wait time 001",1) > 5 then
        --     theNPC.event_step = theNPC.event_step + 1
        -- end
        if GiveItem(theNPC) == true then
            theNPC.event_step = theNPC.event_step + 1
        end
        
    elseif theNPC.event_step == 3 then
        if theNPC.npc_everything_data:Add("time_wait_001",1) == 1 then
            Give_Back_razor(theNPC,theplayer)
        elseif theNPC.npc_everything_data:Get("time_wait_001") >= 3 then
            theNPC.event_step = theNPC.event_step + 1
        end
    elseif theNPC.event_step == 4 then

        inst:Remove()
        theNPC.npc_base_lib:Say("Bye ~ ")
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")

    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_ask_for_razor", fn)
